'use strict';
var mi = mi || {};
mi.datatable = function (setting) {
    this.init(setting);
    this.appendHeader();  // 追加header
    this.datatables();    // 使用datadatable插件
};

mi.datatable.prototype.getTreeData = function (row, data, treeKey) {
    var _self = this;
    var url = this.options.treeView.ajaxUrl;
    if (_self.options.treeView.treeRemote) {
        var queryStr = JSON.stringify(_self.options.treeView.queryCond);
        $.ajax({
            url: url,
            type: 'post',
            dataType: "json",
            data: {
                parentId: treeKey
            },
            beforeSend: function (xhr) {
                showloading();
            },
            success: function (result) {
                closeloading();
                console.log(result.data);
                _self.createTreeView(row, eval(result.data));
            },
            complete: function (xhr, textStatus) {
                closeloading();
            },
            error: function (xhr, textStatus, errorThrown) {
                closeloading();
                Jmts.errTips("请求发生了异常。\n" + xhr.responseText, 3);
            }
        });
    } else {
        var treeData = data.children;
        _self.createTreeView(row, treeData);
    }
}

mi.datatable.prototype.createTreeView = function (row, tData) {
    var trArr = [];
    for (var j = 0; j < tData.length; j++) {

        var sOut = "<tr role='row' class='even'>";
        for (var i = 0; i < this.options.headerName.length; i++) {
            var headerName = this.options.headerName[i].data;
            if (i != 0) {
                if (tData[j][headerName]) {
                    sOut += '<td>' + tData[j][headerName] + '</td>';
                } else {
                    sOut += '<td></td>';
                }
            } else {
                sOut += '<td></td>';
            }
        }
        sOut += '</tr>';
        trArr.push($(sOut));
    }
    //sOut+='</table>';
    row.child(trArr).show();
};

mi.datatable.prototype.init = function (setting) {
    var _self = this;
    var _default = {
        tableId: '',
        oTable: null,
        headerList: [],
        headerName: [],   // 列名需要和后台返回值名对应
        ajaxUrl: '',
        ajaxType: 'post',
        dataSrc: null,
        columnDefs: [],
        paging: true,
        createdRow: null,
        showTree: false,
        paramsData: {},
        treeView: {
            treeKey: '',
            treeData: null,
            treeRemote: false,
            ajaxUrl: '',
            ajaxType: 'post',
            queryCond: {}
        }
    };

    this.options = $.extend({}, _default, setting);
    this.options.oTable = $(this.options.tableId);

    if (setting.showTree) {
        this.options.createdRow = function (row, data, dataIndex) {
            var treeSpan = $("<span class='row-details row-details-close' data_id='" + data[setting.treeView.treeKey] + "'></span>");
            $('td:eq(0)', row).append(treeSpan);

            treeSpan.unbind("click").bind("click", function () {
                var tr = $(this).parents('tr');
                var row = $(_self.options.tableId).DataTable().row(tr);
                if (row.child.isShown())//判断是否已打开            
                {
                    /* This row is already open - close it */
                    $(this).addClass("row-details-close").removeClass("row-details-open");
                    row.child.hide();
                } else {
                    /* Open this row */
                    $(this).addClass("row-details-open").removeClass("row-details-close");
                    _self.getTreeData(row, data, $(this).attr("data_id"));
                }
            });
        };

        this.options.headerName.unshift("dataId");
        this.options.headerList.unshift("  ");
    }

    this.options.headerName = (function () {
        var newArr = [];
        for (var i in _self.options.headerName) {
            newArr.push({"data": _self.options.headerName[i]});
        }
        return newArr;
    })();

};
mi.datatable.prototype.appendHeader = function () {
    var thStr = [];
    $.each(this.options.headerList, function (index, item) {
        thStr.push('<th>' + item + '</th>');
    });
    this.options.oTable.append('<thead><tr>' + thStr.join('') + '</tr></thead>');
};
mi.datatable.prototype.datatables = function () {
    var _self = this;
    this.options.oTable.DataTable({
        info: true,    // 是否显示左下角
        processwing: true,
        serverSide: true,
        searching: false,
        paging: this.options.paging,
        createdRow: this.options.createdRow,
        language: {
            lengthMenu: '每页显示 _MENU_ 条',
            info: '第 _PAGE_ 页 / 总 _PAGES_ 页，总数： _MAX_条',
            infoEmpty: '',
            paginate: {
                first: '第一页',
                last: '最后一页',
                next: '下一页',
                previous: '上一页'
            }
        },

        columns: this.options.headerName,
        columnDefs: this.options.columnDefs,
        ajax: {
            url: this.options.ajaxUrl,
            type: this.options.ajaxType,
            contentType: "application/json",
            dataType: "json",
            data: function (data) {
                var num = data.order[0].column;
                var isOrder = true;
                var columnDefs = _self.options.columnDefs;
                for (var i = 0; i < columnDefs.length; i++) {
                    var columnDef = columnDefs[i];
                    if (columnDef.targets == num && columnDef.orderable == false) {
                        isOrder = false;
                        break;
                    }
                }
                if (isOrder) {
                    var fieldName = data.columns[num].data;
                    data.order[0].fieldName = fieldName;
                } else {
                    data.order = [{}];
                }
                delete data.columns;
                data.queryCond = _self.options.queryCond;
                data.paramsData = _self.options.paramsData;
                var d = JSON.stringify(data);
                return d;
            },
            dataSrc: function (json) {
                var data = json.data;
                if (_self.options.dataSrc && $.isFunction(_self.options.dataSrc)) {
                    data = _self.options.dataSrc(data);
                }
                return data;
            }
        }
    });
};


/*********** 公用函数 ***************/
mi.markLink = function (settings) {
    var _default = {
        href: 'javascript:;',
        txt: '',
        className: '',
        data: []
    };
    var options = $.extend({}, _default, settings);
    // 拼接data属性的数据
    options.data = function () {
        var newArr = [];
        $.each(options.data, function (index, item) {
            var htmlStr = '';
            for (var key in item) {
                htmlStr += ' data-' + key + '="' + item[key] + '" ';
            }
            newArr.push(htmlStr);
        });
        return newArr.join(' ');
    }();
    var result = '';
    result += '<a href="' + options.href + '" class="' + options.className + '" ' + options.data + '>' + options.txt + '</a>';
    return result;
};







